package com.leyou.trade.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.exceptions.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

//下单并生成支付链接
@Component
public class PayHelper {

    @Autowired
    private WXPayConfigImpl wxPayConfig;

    @Autowired
    private WXPay wxPay;

    public String getPayUrl(Long orderId,Long totalFee){
        // 1.准备请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城-商品");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", wxPayConfig.getSpbillCreateIp());
        data.put("trade_type", wxPayConfig.getTradeType());  // 此处指定为扫码支付

        Map<String, String> resp = null;
        try {
            // 2.统一下单
            resp = wxPay.unifiedOrder(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 3.校验支付结果
        // 3.1.通信标示校验
        checkReturnCode(resp);
        // 3.2.业务标示校验
        checkResultCode(resp);
        // 3.3.签名校验
        isSignatureValid(resp);


        //4.返回支付链接
        String codeUrl = resp.get("code_url");
        //判断链接是否为空
        if (StringUtils.isBlank(codeUrl)){
            throw new RuntimeException("获取支付链接失败，链接为空！");
        }

        return codeUrl;
    }



    public void checkReturnCode(Map<String, String> resp) {
        if ("FAIL".equals(resp.get("return_code"))){
            //通信失败
            throw new RuntimeException(resp.get("return_msg"));
        }
    }

    public void checkResultCode(Map<String, String> resp) {
        if ("FAIL".equals(resp.get("result_code"))){
            //业务失败
            throw new RuntimeException(resp.get("err_code_des"));
        }
    }

    public void isSignatureValid(Map<String, String> resp) {
        boolean isSignatureValid;
        try {
            isSignatureValid = wxPay.isResponseSignatureValid(resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!isSignatureValid){
            //签名无效
            throw new RuntimeException("签名无效");
        }
    }
}
